package com.cskaoyan.service.admin.order;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.admin.order.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.admin.order.OrderDetailVo;
import com.cskaoyan.bean.vo.admin.order.UserInfoOfOrderDetailVo;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Aaliyah
 * @date 2022/9/7 10:28
 * @description: 处理订单模块的业务
 */
@Service
public class OrderServiceImpl implements OrderService {

    // order表 - order_status
    private static final Short UNPAID = 101;    // 未付款
    private static final Short USER_CANCEL = 102;    // 用户取消
    private static final Short SYSTEM_CANCEL = 103;    // 系统取消
    private static final Short ALREADY_PAID = 201;    // 已付款
    private static final Short APPLY_REFUND = 202;    // 申请退款
    private static final Short ALREADY_REFUND = 203;    // 已退款
    private static final Short ALREADY_SHIP = 301;    // 已发货
    private static final Short USER_RECEIVE = 401;    // 用户收货
    private static final Short SYSTEM_RECEIVE = 402;    // 系统收货

    // order - aftersale_status 订单售后状态
    private static final Short APPLY_ALLOWED_AFS = 0;
    private static final Short USER_APPLYED_AFS = 1;
    private static final Short ADMIN_APPROVED_AFS = 2;
    private static final Short REFUND_SUCESS_AFS = 3;
    private static final Short ADMIN_REJECT_AFS = 4;
    private static final Short USER_CANCEL_AFS = 5;

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    MarketChannelMapper marketChannelMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;


    /**
     * @description: 根据Bo提供的信息，向Mapper发送查询请求    url:/admin/order/list
     * @date: 2022/9/7 10:29
     * @param: [orderListBo] 返回查询到的订单数据
     */
    @Override
    public CommonData orderList(OrderListBo orderListBo) {

        // 使用example方法，将条件封装进Example对象中
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        orderExample.setDistinct(true);
        orderExample.setOrderByClause(orderListBo.getSort() + " " + orderListBo.getOrder());
        criteria.andDeletedEqualTo(false);
        // 判断其他条件是否为空，若不为空，加入example中
        if (orderListBo.getStart() != null) {
            criteria.andAddTimeBetween(orderListBo.getStart(), orderListBo.getEnd());
        }
        if (orderListBo.getOrderStatusArray() != null) {
            criteria.andOrderStatusIn(Arrays.asList(orderListBo.getOrderStatusArray()));
        }
        //宾文杰 日期查询
        if (orderListBo.getTimeArray() != null&&orderListBo.getTimeArray().length==2) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            criteria.andPayTimeBetween(orderListBo.getTimeArray()[0],orderListBo.getTimeArray()[1]);
        }
        if (orderListBo.getOrderId() != null) {
            criteria.andIdEqualTo(orderListBo.getOrderId());
        }
        if (orderListBo.getUserId() != null) {
            criteria.andUserIdEqualTo(orderListBo.getUserId());
        }
        if (orderListBo.getOrderSn() != null) {
            criteria.andOrderSnLike("%" + orderListBo.getOrderSn() + "%");
        }

        // 根据条件进行分页查询，并获得分页信息
        PageHelper.startPage(orderListBo.getPage(), orderListBo.getLimit());
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(orderExample);
        PageInfo<MarketOrder> pageInfo = new PageInfo<>(marketOrders);

        return CommonData.data(pageInfo);
    }

    /**
     * @description: 根据传入的订单id对多个表进行查询，最后将结果封装进Vo返回
     * @date: 2022/9/7 16:45
     * @param: [id]
     */
    @Override
    public OrderDetailVo orderDetail(Integer id) {

        // 根据订单id查询订单信息
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(id);

        // 根据订单id查询订单商品列表
        MarketOrderGoodsExample OrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = OrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(id);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(OrderGoodsExample);

        // 根据订单信息中的用户id查询订单的用户信息
        MarketUser marketUser = marketUserMapper.selectByPrimaryKey(marketOrder.getUserId());
        UserInfoOfOrderDetailVo userInfo = new UserInfoOfOrderDetailVo();
        userInfo.setNickname(marketUser.getNickname());
        userInfo.setAvatar(marketUser.getAvatar());

        // 将查询结果封装进Vo并返回
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setOrderGoods(marketOrderGoods);
        orderDetailVo.setUser(userInfo);
        orderDetailVo.setOrder(marketOrder);
        return orderDetailVo;
    }

    /**
     * @description: 根据传入的id找到订单，并修改订单状态
     * @date: 2022/9/8 16:05
     * @param: [orderRefundBo] 封装了订单id和退款金额
     */
    @Override
    public void orderRefund(OrderRefundBo orderRefundBo) {

        // 将订单id和需要修改的内容封装进PO
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderRefundBo.getOrderId());
        marketOrder.setRefundAmount(orderRefundBo.getRefundMoney());
        marketOrder.setRefundTime(getNow());
        marketOrder.setUpdateTime(getNow());
        marketOrder.setEndTime(getNow());
        marketOrder.setAftersaleStatus(ADMIN_APPROVED_AFS);
        marketOrder.setOrderStatus(ALREADY_REFUND);

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    private Date getNow() {
        return new Date(System.currentTimeMillis());
    }

    /**
     * @description: 根据传入的订单id信息，更新订单状态和快递信息，更新数据更新时间
     * @date: 2022/9/8 16:41
     * @param: [orderShipBo] 封装了订单id和快递信息
     */
    @Override
    public void orderShip(OrderShipBo orderShipBo) {

        // 将id和需要修改的信息封装进PO
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderShipBo.getOrderId());
        marketOrder.setOrderStatus(ALREADY_SHIP);
        marketOrder.setShipChannel(orderShipBo.getShipChannel());
        marketOrder.setShipSn(orderShipBo.getShipSn());
        marketOrder.setShipTime(getNow());
        marketOrder.setUpdateTime(getNow());

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    /**
     * @description: 将所有快递公司数据传送到前端
     * @date: 2022/9/13 1:17
     * @param: []
     */
    @Override
    public List<MarketChannel> orderChannel() {
        List<MarketChannel> marketChannels = marketChannelMapper.selectAll();
        return marketChannels;
    }

    @Override
    public int orderDelete(OrderIdBo orderIdBo) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderIdBo.getOrderId());
        Short orderStatus = marketOrder.getOrderStatus();
        List<Short> orderStatusList = new ArrayList<>();
        orderStatusList.add(USER_CANCEL);
        orderStatusList.add(SYSTEM_CANCEL);
        orderStatusList.add(ALREADY_REFUND);
        orderStatusList.add(USER_RECEIVE);
        if (orderStatusList.contains(orderStatus)){
            marketOrder.setDeleted(true);
            marketOrder.setUpdateTime(getNow());
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
            return 200;
        }
        return 623;
    }

    @Override
    public int orderReply(OrderReplyBo orderReplyBo) {
        MarketComment marketComment = marketCommentMapper.selectByPrimaryKey(orderReplyBo.getCommentId());
        // 已回复
        if(marketComment.getAdminContent()!=null){
            return 622;
        }
        marketComment.setAdminContent(orderReplyBo.getContent());
        marketComment.setUpdateTime(getNow());
        marketCommentMapper.updateByPrimaryKeySelective(marketComment);
        return 200;
    }
}
